/**
 * Created by alice on 2016/7/11.
 * 组件的重写和封装
 */
define(function(require, exports, module){
    //引入模块
    var $=require("jquery");
    var components=function(){

    };
    /**
     * 重写alert
     */
    components.alert=function(val){
        var op = {
            "type" : "alert",
            "timer" : 2000,
            "className" : {
                "type" : "",
                "flash" : "alertFlash"
            }
        };

        if(val.constructor === Object){
            $.extend(op,val);
        }else{
            op.val = val;
        }
        if(op.val.constructor !== String){
            op.val = op.val.toString();
        }
        if(!op.val || (op.val.constructor !== String  && op.val.constructor !== String))
            return "not value";

        var $alert = $("<div class='alertBox'>").addClass(op.className[op.type]),
            $text = $("<div class='alertText'>").html(op.val).appendTo($alert),
            $ok = $("<div class='alertBtn'>").html("确定").appendTo($alert),
            _mask;
        if(op.type == "flash"){
            _mask = new components.mask("mask_flash");
        }else{
            _mask = new components.mask();
        }
        _mask.show();

        function closeAlert(){
            $alert.remove();
            _mask.hide();
            delete _mask;
            op.callback && op.callback();
        }

        $ok.on("touchend",function(){
            $alert.on("webkitTransitionEnd",closeAlert).removeClass("alertShow");
        });

        $alert.appendTo("body");
        setTimeout(function(){
            $alert.addClass("alertShow");
            if(op.type && op.type == "flash"){
                setTimeout(closeAlert,op.timer);
            }
        });
    };
    /**
     * alert新样式
     * @param val
     * @returns {string}
     */
    components.alert1=function(val){
        var op = {
            "type" : "alert",
            "timer" : 2000,
            "className" : {
                "type" : "",
                "flash" : "alertFlash1"
            }
        };

        if(val.constructor === Object){
            $.extend(op,val);
        }else{
            op.val = val;
        }
        if(op.val.constructor !== String){
            op.val = op.val.toString();
        }
        if(!op.val || (op.val.constructor !== String  && op.val.constructor !== String))
            return "not value";

        var $alert = $("<div class='alertBox1'>").addClass(op.className[op.type]),
            $text = $("<div class='alertText1'>").html(op.val).appendTo($alert),
            $ok = $("<div class='alertBtn1'>").html("确定").appendTo($alert),
            _mask;
        if(op.type == "flash"){
            _mask = new components.mask("mask_flash");
        }else{
            _mask = new components.mask();
        }
        _mask.show();

        function closeAlert(){
            $alert.remove();
            _mask.hide();
            delete _mask;
            op.callback && op.callback();
        }

        $ok.on("touchend",function(){
            $alert.on("webkitTransitionEnd",closeAlert).removeClass("alertShow");
        });

        $alert.appendTo("body");
        setTimeout(function(){
            $alert.addClass("alertShow");
            if(op.type && op.type == "flash"){
                setTimeout(closeAlert,op.timer);
            }
        });
    };
    //自定义遮罩
    components.mask=function(type,callback){

        var timer,
            that = this,
            $mask = $("<div class='maskBar'><i></i></div>").appendTo("body");

        if(type && type.constructor === Function){
            callback = type;
        }else{
            $mask.addClass(type);
        }

        this.show = function(){
            $mask.addClass("show");
            if(type == "loading"){
                timer = setTimeout(function(){
                    components.alert({
                        "val" : "网络不给力<br>请重试",
                        "type" : "flash",
                        "callback" : function(){
                            that.hide();
                        }
                    });
                },15000);
            }
        };

        this.hide = function(){
            if(type == "loading"){
                clearTimeout(timer);
            }
            $mask.on("webkitTransitionEnd",function(){
                $(this).remove();
                callback && callback();
            }).removeClass("show");
        };

    };
    //滑动列表（左侧）
    $.fn.lrTouchMove = function(){
        var _this = this,
            _touchStatus = false,
            _status = false,
        // _boxStatus = 0,
            _x = 0,
            _y=0,
            _ex=0,
            _ey=0,
            x=0,
            y=0,
            _moveX = 0,
            _w,
            _hideW = 5.3;

        this.bind({
            "touchstart" : function(event){
                if(!this.dataset.boxStatus){
                    this.dataset.boxStatus = 0;
                }
                $(this).css("transition","");
                _status = true;
                _w = $(this).width();
                //开始滑动x坐标
                _x = event.originalEvent.touches[0].clientX;
                //开始滑动时y 坐标
                _y=event.originalEvent.changedTouches[0].pageY;
            },
            "touchmove" : function(event){
                var _n = Number(this.dataset.boxStatus);
                //滑动结束 时的xy坐标
                _ex=event.originalEvent.touches[0].clientX;
                _ey=event.originalEvent.changedTouches[0].pageY;
                x=_ex-_x;
                y=_ey-_y;
                //判断右往左滑动

                _moveX = (event.originalEvent.touches[0].clientX - _x) / _w;
                if(Math.abs(x) > Math.abs(y) && Math.abs(x)<6 && Math.abs(y)<6){
                    console.log("right 2 left");
                    event.stopPropagation();
                    if(_status && (_n != 0 || _moveX < 0)){
                        $(this).css("-webkit-transform","translate3d(" + (_n + (_hideW * _moveX * 2)) + "rem,0,0)");
                        if(navigator.userAgent.toLocaleLowerCase().indexOf("mi") >= -1){
                            return false;
                        }
                    }

                }

            },
            "touchend" : function(event){
                if(Math.abs(x) > Math.abs(y) && x < 0){
                    event.stopPropagation();
                }
                $(this).css("transition","all .1s ease");
                var __x = 0;
                if(this.dataset.boxStatus == 0 && _moveX < -0.3){
                    this.dataset.boxStatus = -_hideW;
                }else if(this.dataset.boxStatus < 0 && _moveX < 0.15){
                    this.dataset.boxStatus = -_hideW;
                }else{
                    this.dataset.boxStatus = 0;
                }
                $(this).css("-webkit-transform","translate3d(" + this.dataset.boxStatus + "rem,0,0)");
                _status = false;
            }
        });
        return this;
    };
    /**
     * 触屏点击（无延迟）
     */
    $.fn.ontouch = function(callback,bool){

        var _x,_y,_s,
            _t = {
                s : function(event){
                    var t = getTouch(event);
                    _x = t.clientX;
                    _y = t.clientY;
                    _s = true;
                },
                m : function(event){
                    if(_s){
                        var t = getTouch(event);
                        if(_x != t.clientX || _y != t.clientY){
                            _s = false;
                        }
                    }
                },
                e : function(event){
                    if(_s){
                        callback.call(this);
                        if(bool){
                            event.preventDefault();
                            return false;
                        }
                    }
                }
            };

        function getTouch(event){
            return event.originalEvent.touches[0] ? event.originalEvent.touches[0] : event;
        }

        this.bind({
            "touchstart" : _t.s,
            "touchmove" : _t.m,
            "touchend" : _t.e
        });

        return this;

    };
    /**
     *对话框
     * @param val
     * @param callback 回调
     * @param cancelCallback 取消的回调
     */

    components.confirm=function(val,callback,cancelCallback){
        var op = {
            "passText" : "确认",
            "cancelText" : "取消"
        };

        if(val.constructor === Object){
            $.extend(op,val);
        }else{
            op.val = val;
            op.passCallback = callback;
            op.cancelCallback = cancelCallback;
        }
        if(op.val.constructor !== String){
            op.val = op.val.toString();
        }

        if(!op.val || op.val.constructor !== String || !op.passCallback || op.passCallback.constructor !== Function)
            return "not value or callback";

        var $confirm = $("<div class='confirmBox'>"),
            $text = $("<div class='confirmText'>").html(op.val).appendTo($confirm),
            $ok = $("<div class='confirmOk'>").html(op.passText).appendTo($confirm),
            $cancel = $("<div class='confirmCancel'>").html(op.cancelText).appendTo($confirm),
            _mask = new components.mask();
        _mask.show();

        $ok.on("touchend",function(){
            $confirm.on("webkitTransitionEnd",function(){
                $(this).remove();
                delete _mask;
                _mask.hide();
                op.passCallback && op.passCallback();
            }).removeClass("confirmShow");
        });
        $cancel.on("touchend",function(){
            $confirm.on("webkitTransitionEnd",function(){
                $(this).remove();
                delete _mask;
                _mask.hide();
                op.cancelCallback && op.cancelCallback();
            }).removeClass("confirmShow");
        });

        $confirm.appendTo("body");
        setTimeout(function(){
            $confirm.addClass("confirmShow");
        });
    };


    /**
     * 给阅读绑定收藏和分享 的方法
     */
    $.fn.collectnews = function(){
        // if(window.___collectnews_over){
        // 	return;
        // }
        // window.___collectnews_over = true;
        var _  = this;
        //收藏
        _.find("i.icon-redstars,i.icon-greystars").ontouch(function(){
            //判断是否登录
            if(!gm.user.isLoginDoctor()){
                gm.pul.toUrl('goodm://login');
                return;
            }
            var _this = this;
            var _class = $(this).attr("class");
            var _newsid = $(this).parent().parent().attr("contentuuid");

            if(_class == "icon-redstars"){
                _class = "icon-greystars";
                var _favid = $(this).parent().parent().attr("favid");
                //删除收藏
                gm.user.delFavorites(_favid,function(data){
                    var result=$(_this).parent().siblings(".asbg").find(".videomz").find(".contentcount").children().html();
                    $(_this).parent().siblings(".asbg").find(".videomz").find(".contentcount").children().html(--result);
                });
            }else{
                _class = "icon-redstars";
                //添加收藏
                gm.user.addFavorite(_newsid,1,function(data){
                    $(_this).parent().parent().attr("favid",data)
                    var result=$(_this).parent().siblings(".asbg").find(".videomz").find(".contentcount").children().html();
                    $(_this).parent().siblings(".asbg").find(".videomz").find(".contentcount").children().html(++result);
                });
            }
            //_czc.push(["_trackEvent","阅读","收藏","",'','i.icon-redstars,i.icon-greystars']);
            $(this).attr("class",_class);
        },true);

        //分享
        _.find(".icon-mycollection,.icon-mycollectiongray").ontouch(function(){
            //判断是否登录
            if(!gm.user.isLoginDoctor()){
                gm.pul.toUrl('goodm://login');
                return;
            }
            var _ = $(this);
            var _contentUuid = $(this).parents("li").attr("contentuuid");

            if (!_contentUuid) {
                _contentUuid = $(this).parents("dd").attr("contentuuid");
            }
            var p = _.parent().parent();

            var obj = {
                "title":p.find(".videomz h2").text(),
                "desc":p.find(".videomz h2").text(),
                "img":p.find("img").attr("src"),
                "link":window._interfacePath + "/html/thedoctorinformation/" + p.find(".videomz h2 a").attr("href")
            };

            gm.share(obj,function(){
                $.getDate({
                    page:"doctor",
                    inter:"addDoctorShare",
                    data:{contentUuid:_contentUuid,doctorUuid:gm.user.getDoctor()},
                    callback:function(data){
                        //_czc.push(["_trackEvent","阅读","分享","",'','addDoctorShare']);
                    }
                });
            });
        },true);

        return _;
    };

    /**
    *设置开关
     */
    $.fn.settingOnOff=function(callback){
        $(this).bind({
            "touchend":function(){
                if($(this).hasClass("off")){
                    $(this).attr("class","on");
                }else{
                    $(this).attr("class","off");
                }
                callback.call(this,this.className);
            }
        });
        return this;
    };
    //暴露调用方法
    module.exports=components;
});
